// pages/eat/index.js
import {
  userhealthyList,
  getListByUser,
  healthyList,
  getFoodCategoryList,
  addHealthy
} from '../../utils/api';
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    tagList: [],
    current: 0,
    nav: [{
        name: '能吃',
        id: 2,
      },
      {
        name: '慎吃',
        id: 1,
      },
      {
        name: '不能吃',
        id: 0,
      },
    ],
    list: [],
    isLoading: true,
    filterList: [],
    showType: false,
    currentPage: 1, // 当前页
    totalPages: 1, // 总页数
    categoryId: null,
    imgUrl: app.globalData.imgUrl,
    wxImgUrl: app.globalData.wxImgUrl,
    navBarHeight: '', //头高度
    statusBarHeight: '', //状态栏高度
    showModal: false, // 设置健康状况
    notSet: false, // 是否设置健康状况
    allDiseaseList: [], // 所有疾病列表
    selectedArr: [], // 选中的健康状况
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getDiseaseList()
    //获取头部高度
    let navBarHeightinfo = app.publicFun.navBarHeightinfo()
    this.setData({
      navBarHeight: navBarHeightinfo[0],
      statusBarHeight: navBarHeightinfo[1]
    })
    if (wx.getStorageSync('token') != '') {
      this.gethealthy();
      this.getListData();
      this.getFilterData();
    }
  },
  onShow() {
    if (wx.getStorageSync('token') == '') {
      this.selectComponent('#modeShow').modeShow(); // 通过实例调用组件事件
    }
    if (wx.getStorageSync('token') != '' && wx.getStorageSync('num') == 1) {
      this.selectComponent('#modeShow').off();
      wx.setStorageSync('num', 2);
      this.gethealthy();
      this.getListData();
      this.getFilterData();
    }
  },
  gethealthy(num) {
    userhealthyList({}).then(res => {
      this.setData({
        tagList: res,
      });
      if (num == 1) {
        this.setData({
          list: [],
          currentPage: 1
        });
        this.getListData();
      }
    });
  },
  // 跳转详情
  handleEatDetail(e) {
    wx.navigateTo({
      url: `/pages/food-detail/index?id=${e.currentTarget.dataset.id}`,
    });
  },
  handlerHeadl() {
    wx.navigateTo({
      url: '/user/pages/addhealthy/index?type=1',
    });
  },
  //点击切换
  handlerTab(e) {
    let index = e.currentTarget.dataset.id;
    this.setData({
      current: index,
      list: [],
      currentPage: 1
    });
    this.getListData();
  },
  handlerType(e) {
    let index = e.currentTarget.dataset.id;
    this.setData({
        showType: false,
        categoryId: index,
        list: []
      },
      () => {
        this.getListData();
      },
    );
  },
  // 获取列表数据
  async getListData() {
    wx.showLoading({
      title: '正在加载中',
      icon: 'none',
    });
    try {
      const res = await getListByUser({
        pageSize: 10,
        pageNum: this.data.currentPage,
        eatType: this.data.current,
        categoryId: this.data.categoryId,
      });
      if (res) {
        this.setData({
          list: this.data.list.concat(res.records),
          totalPages: res.pages,
          isLoading: true,
        });
      }else{
        this.setData({
          showModal:true,
          notSet:true
        })
      }
      wx.hideLoading({
        success: res => {},
      });
    } catch (error) {
      wx.hideLoading({
        success: res => {},
      });
    }
  },
  // 获取筛选数据列表
  async getFilterData() {
    try {
      const res = await getFoodCategoryList();
      if (res) {
        this.setData({
          filterList: res,
        });
      }
    } catch (err) {}
  },
  //点击筛选
  handlerAll() {
    this.setData({
      showType: !this.data.showType,
      currentPage: 1
    });
  },
  getDiseaseList(){
    healthyList().then(res=>{
      if(res){
        this.setData({
          allDiseaseList:res
        })
      }
    }).catch (err =>{console.log(err)})
  },
  openModal(){
    this.setData({
      showModal:true
    })
  },
  setCurrentPerson(e){
    const currentItem = e.currentTarget.dataset.item 
    let arr = []
    if(this.data.selectedArr && this.data.selectedArr.length > 0){
      const hasType2 = this.data.selectedArr.some(item=>{
        return item.type === 2
      })
      if(!hasType2){
        this.setData({
          selectedArr:this.data.selectedArr.concat([currentItem])
        })
        if(currentItem.type === 2){
          arr = this.data.allDiseaseList.map(item=>{
            if(item.type === 2 ){
              item.selected = !item.selected
            }else{
              item.selected = false
            }
            return {...item}
          })
        }else{
          arr = this.data.allDiseaseList.map(item=>{
            if(item.id === currentItem.id){
              item.selected =   !item.selected
            }
            return {
              ...item
            }
          })
        }
      }else{
        arr = this.data.allDiseaseList.map(item=>{
          if(item.type === 2 ){
            item.selected = !item.selected
          }else{
            if( currentItem.id === item.id){
              item.selected = true
            }else{
              item.selected = false
            }
          }
          return {...item}
        })
      }
    }else{
      this.setData({
        selectedArr:this.data.selectedArr.concat([currentItem])
      })
      arr = this.data.allDiseaseList.map(item=>{
        if(item.id === currentItem.id){
          item.selected =   true
        }
        return {
          ...item
        }
      })
    }
    this.setData({
      allDiseaseList:arr
    })
    const currentSelected = this.data.allDiseaseList.filter(item=>{
      return item.selected
    })
    this.setData({
      selectedArr:currentSelected
    })
  },
  updateUser(){
    if(this.data.selectedArr.length === 0){
      wx.showToast({
        icon:'none',
        title: '请选择你的健康状况',
      })
    }
    const ids = this.data.selectedArr.map(item=>{
      return item.id
    })
    wx.showLoading({
      title: '提交中',
    })
    addHealthy({
      diseaseIds:ids,
      userId:wx.getStorageSync('userid')
    }).then(res=>{
      wx.hideLoading();
      if(res){
        this.setData({
          showModal:false
        })
        wx.showToast({
          title: '更新成功',
          icon: 'none'
        })
        this.gethealthy()
      }
    })
  },
  onReachBottom: function () {
    if (this.data.isLoading && this.data.currentPage < this.data.totalPages) {
      this.setData({
        isLoading: false,
        currentPage: this.data.currentPage + 1,
      }, () => {
        this.getListData();
      });
    }
  },
});